#include <std.h>
#include <tsk.h>
#include <stdio.h>
#include <csl.h>
#include <csl_cache.h>
#include <csl_dat.h>
#include <chan.h>
#include <scom.h>
#include <utl.h>
#include <ialg.h>

#include "fvid.h"
#include "celljpegenc_ti.h"
#include "celljpegdec_ti.h"
#include "appmain.h"
#include "appThreads.h"
#include "tskProcess.h"
#include "appBiosObjects.h"  
#include "cap_dis_size.h"

IJPEGENC_Params   jpegencParams;
IJPEGDEC_Params   jpegdecParams;


#pragma DATA_SECTION(jpg_img,   ".user_data_ext")
#pragma DATA_ALIGN( jpg_img,   128)
unsigned char jpg_img[128 * 2000];

#pragma DATA_ALIGN(dec_out_y, 128);
#pragma DATA_ALIGN(dec_out_u, 128);
#pragma DATA_ALIGN(dec_out_v, 128);
unsigned char dec_out_y[NUM_LINES * LINE_SZ];
unsigned char dec_out_u[(NUM_LINES * LINE_SZ) >> 2];
unsigned char dec_out_v[(NUM_LINES * LINE_SZ) >> 2];


static Void checkMsg();


ThrProcess thrProcess;

void tskProcessInit()
{
    int chanNum;
    ICELL_Obj  *cell;
    ICC_Handle  inputIcc;
    ICC_Handle  outputIcc;

    /*----------------------------------------------------*/
    /* Call JPEG specific user initialization if any.     */
    /*----------------------------------------------------*/

    JPEGENC_TI_init();
    JPEGDEC_TI_init();

    /*----------------------------------------------------*/
    /* Set up params for all XDAIS algorithms.            */
    /*----------------------------------------------------*/

    jpegencParams = IJPEGENC_PARAMS;
    jpegdecParams = IJPEGDEC_PARAMS;

    for (chanNum = 0; chanNum < PROCESSNUMCHANNELS ; chanNum++)
    {
        /*
         * JPEGENC: create an input and output linear ICC:
         * The address to the ICC's will be set in the thrProcessRun()
         * function via the ICC_setBuf().
         */
        ICELL_Obj   defaultCell = ICELL_DEFAULT;

        cell = &thrProcess.cellListEncode[(chanNum*PROCESSNUMCELLS) + 0];
        *cell                = defaultCell;
        cell->name           = "JPEGENC";
        cell->cellFxns       = &JPEGENC_CELLFXNS;
        cell->algFxns        = (IALG_Fxns *)&JPEGENC_IJPEGENC;
        cell->algParams      = (IALG_Params *)&IJPEGENC_PARAMS;
        cell->scrBucketIndex = THRIOSSCRBUCKET;

        inputIcc  = (ICC_Handle)ICC_linearCreate(NULL, 0);
        UTL_assert( inputIcc != NULL);

        outputIcc = (ICC_Handle)ICC_linearCreate(NULL, 0);
        UTL_assert( outputIcc != NULL);

        // Only one input and one output ICC are needed.
        CHAN_regCell( cell, &inputIcc, 1, &outputIcc, 1 );

        // Setup Encode Parameters
        thrProcess.cellListEncode[(chanNum*PROCESSNUMCELLS) + 0].algParams =
                                                (IALG_Params *)&IJPEGENC_PARAMS;

        UTL_logDebug1("JPEGEncoder registerd Channel Number: %d", chanNum);

        /*
         * JPEGDEC: create an input and output linear ICC:
         * The address to the ICC's will be set in the thrProcessRun()
         * function via the ICC_setBuf().
         */
        cell = &thrProcess.cellListDecode[(chanNum*PROCESSNUMCHANNELS) + 0];
        *cell                = defaultCell;
        cell->name           = "JPEGDEC";
        cell->cellFxns       = &JPEGDEC_CELLFXNS;
        cell->algFxns        = (IALG_Fxns *)&JPEGDEC_IJPEGDEC;
        cell->algParams      = (IALG_Params *)&IJPEGDEC_PARAMS;
        cell->scrBucketIndex = THRIOSSCRBUCKET;

        inputIcc  = (ICC_Handle)ICC_linearCreate(NULL, 0);
        UTL_assert( inputIcc != NULL);

        outputIcc = (ICC_Handle)ICC_linearCreate(NULL, 0);
        UTL_assert( outputIcc != NULL);

        // Only one input and one output ICC are needed.
        CHAN_regCell( cell, &inputIcc, 1, &outputIcc, 1 );

        // Setup Decode Parameters
        thrProcess.cellListDecode[(chanNum*PROCESSNUMCELLS) + 0].algParams =
                                               (IALG_Params *)&IJPEGDEC_PARAMS;

        UTL_logDebug1("JPEGDecoder registerd Channel Number: %d", chanNum);
    }

    memset(dec_out_y, 0x0,  sizeof(dec_out_y));
    memset(dec_out_u, 0x80, sizeof(dec_out_u));
    memset(dec_out_v, 0x80, sizeof(dec_out_v));

    CACHE_clean(CACHE_L2ALL, 0, 0);
    CACHE_clean(CACHE_L2ALL, 0, 0);
}

void tskProcessStart()
{
    int chanNum;
    for( chanNum=0; chanNum < PROCESSNUMCHANNELS; chanNum++ )
    {
        // open the encode channel: this causes the algorithms to be created
        CHAN_open( &thrProcess.chanListEncode[chanNum],
                   &thrProcess.cellListEncode[(chanNum*PROCESSNUMCELLS)],
                   PROCESSNUMCELLS, NULL );

        // open the decode channel: this causes the algorithms to be created
        CHAN_open( &thrProcess.chanListDecode[chanNum],
                   &thrProcess.cellListDecode[(chanNum*PROCESSNUMCELLS)],
                   PROCESSNUMCELLS, NULL );

    }
}


static Void checkMsg()
{
    CtrlMsg rxMsg;
    Int index;
    Int quality;
    ICELL_Handle handle;

    IJPEGENC_Params jpegencParams;
    int cell_no;

    // check message in "mbxProc"
    while( MBX_pend( &mbxProcess, &rxMsg, 0) )
    {
        switch (rxMsg.cmd)
        {
            case MSGFRAMECHANGE:  // frame ratio value changed
            {
                index = rxMsg.arg1;  // get the index number
                UTL_assert( (index >= 0) && (index < PROCESSNUMCHANNELS));
                // update the local value
                if (index < PROCESSNUMCHANNELS)
                    thrProcess.frameRateControl[index] = rxMsg.arg2;

                break;
            }

            case MSGQUALCHANGE: //quality rate value changed
            {
                index = rxMsg.arg1;  // get the index number
                UTL_assert( (index >= 0) && (index < PROCESSNUMCHANNELS));
                if (index < PROCESSNUMCHANNELS)
                {
                    jpegencParams =  IJPEGENC_PARAMS;
                    cell_no = rxMsg.arg2;
                    UTL_assert( (cell_no >= 0) && (cell_no < PROCESSNUMCELLS));

                    quality = rxMsg.arg3;
                    UTL_assert( (quality >= 0) &&
                                 (quality <= 100));

                    jpegencParams.quality = quality;

                    if ((quality > 0) && (quality <= 100))
                    {
                       handle = &(thrProcess.cellListEncode[index]);

                       thrProcess.cellListEncode[cell_no].cellFxns->cellControl
                       (
                           handle,
                          (IALG_Cmd) (IJPEG_SETSTATUS),
                          (IALG_Status*)(&(jpegencParams))
                       );
                    }
               }

               break;
            }

            default:
                break;
        }
    }
}


extern int SystemReady;


void tskProcess()
{
    int i;
    ScomMessage *pMsgBuf;
    void *inBuf[3];
    void *outBuf[3];
    int  jpg_size;
    int framenum=0;
    CHAN_Handle chanHandle;
    SCOM_Handle fromInputtoProc,fromProctoInput;
    SCOM_Handle fromOuttoProc,fromProctoOut;

    fromInputtoProc = SCOM_open("INTOPROC");
    fromProctoInput = SCOM_open("PROCTOIN");
    fromProctoOut   = SCOM_open("PROCTOOUT");
    fromOuttoProc   = SCOM_open("OUTTOPROC");

    while(1)
    {
        checkMsg();

        framenum++;

        for(i=0; i<PROCESSNUMCHANNELS; i++)
        {
            // Get Input Buffer
            pMsgBuf = SCOM_getMsg(fromInputtoProc, SYS_FOREVER);

            // If we're skipping this frame, just give the SCOM msg
            // back to the input function and continue the for loop.
            if( thrProcess.frameRateControl[i] != 0 &&
                (framenum % thrProcess.frameRateControl[i]) )
            {
                // Tell the capture routine we're done
                SCOM_putMsg(fromProctoInput,pMsgBuf);
                continue;
            }

            //
            // Handle Encode Channel
            //
            chanHandle = &thrProcess.chanListEncode[i];
            chanHandle->state = CHAN_ACTIVE;

            // Channel Input
            inBuf[0] = pMsgBuf->bufY;
            inBuf[1] = pMsgBuf->bufU;
            inBuf[2] = pMsgBuf->bufV;
            ICC_setBuf( chanHandle->cellSet[0].inputIcc[0],
                        inBuf, sizeof(void *) * 3 );

            // Channel Output
            outBuf[0] = &jpg_size;
            outBuf[1] = jpg_img;
            ICC_setBuf( chanHandle->cellSet[0].outputIcc[0],
                        outBuf, sizeof(void *) * 2 );

            // Execute Channel
            CHAN_execute( chanHandle, framenum );

            // Tell the capture routine we're done
            SCOM_putMsg( fromProctoInput, pMsgBuf );

            //
            // Handle Decode Channel
            //
            chanHandle = &thrProcess.chanListDecode[i];
            chanHandle->state = CHAN_ACTIVE;

            inBuf[0] = &jpg_size;
            inBuf[1] = jpg_img;
            ICC_setBuf( chanHandle->cellSet[0].inputIcc[0],
                        inBuf, sizeof(void *) * 2 );

            outBuf[0] = (void *)dec_out_y;
            outBuf[1] = (void *)dec_out_u;
            outBuf[2] = (void *)dec_out_v;
            ICC_setBuf( chanHandle->cellSet[0].outputIcc[0],
                        outBuf, sizeof(void *) * 3 );

            // Execute Channel
            CHAN_execute( chanHandle, framenum );

            // Send the buffer to the display task
            pMsgBuf = SCOM_getMsg(fromOuttoProc, SYS_FOREVER);

            pMsgBuf->bufY = (void *)dec_out_y;
            pMsgBuf->bufU = (void *)dec_out_u;
            pMsgBuf->bufV = (void *)dec_out_v;
            SCOM_putMsg(fromProctoOut,pMsgBuf);
        }
    }
}




